# _*_ coding: utf-8 _*_
from . import home
from app import db
from app.home.forms import LoginForm, RegisterForm, SuggetionForm, userForm
from app.models import User, Artist, Song, Collect, Tag, Comment
from flask import render_template, url_for, redirect, flash, session, request, jsonify
from functools import wraps
import time
import os
import matplotlib.pyplot as plt
from pylab import mpl
import random


base = os.path.dirname(__file__)
# song_path = base + '/../static/song/'
img_path = base + '/../static/artist/'
song_path = base

def admin_login(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session['flag'] == 0:
            return redirect(url_for("home.index"))
        return f(*args, **kwargs)

    return decorated_function


def user_login(f):
    """
    登录装饰器
    """

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if "user_id" not in session:
            return "<script>alert('请先登录');history.go(-1)</script>"
        return f(*args, **kwargs)

    return decorated_function


@home.route("/contentFrame")
def contentFrame():
    """
    主页面
    """
    print("主界面")
    hot_artist = Artist.query.filter_by(isHot=1).limit(20).all()  # 获取歌手数据
    hot_song = Song.query.order_by(Song.hits.desc()).limit(10).all()  # 获取歌曲数据

    page = request.args.get('page', type=int)  # 获取page参数值
    page_data = Artist.query.paginate(page=page, per_page=5)
    return render_template('home/contentFrame.html', hot_artist=hot_artist, hot_song=hot_song,page_data=page_data)  # 渲染模板


@home.route("/")
def index():
    """
    首页
    """
    return render_template('home/index.html')  # 渲染模板


@home.route("/login/", methods=["GET", "POST"])
def login():
    """
    登录
    """

    if request.method == 'POST':
        username = request.form.get("username")
        print(username)
        pwd = request.form.get("pwd")
        user = User.query.filter_by(username=username).first()  # 获取用户信息

        res = {}
        # 检测用户名
        if not user:
            res['status'] = -1
            res['message'] = '用户名不存在'
            return jsonify(res)
        # 检测密码
        if not user.check_pwd(pwd):  # 调用check_pwd()方法，检测用户名密码是否匹配
            res['username'] = user.username
            res['status'] = -2
            res['message'] = '用户名和密码不匹配'
            return jsonify(res)

        session["user_id"] = user.id  # 将user_id写入session, 后面用户判断用户是否登录
        session["username"] = user.username  # 将user_id写入session, 后面用户判断用户是否登录
        print(session["user_id"])
        session['flag'] = user.flag
        res['status'] = 1
        res['message'] = '登录成功'
        return jsonify(res)

    return render_template("home/login.html")


@home.route("/register/", methods=["GET", "POST"])
def register():
    """
    注册功能
    """
    if request.method == "POST":  # 提交注册表单
        username = request.form.get("username")
        pwd = request.form.get("pwd")
        # 判断用户名是否存在
        user = User.query.filter_by(username=username).first()  # 获取用户信息
        if user:
            res = {}
            res['status'] = -2
            res['message'] = '该用户已存在'
            return jsonify(res)
        # 写入到user表
        try:
            # 为User类属性赋值
            user = User(
                username=username,  # 用户名
                pwd=pwd,  # 对密码加密
                flag=0
            )
            db.session.add(user)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '注册成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '注册失败'
        return jsonify(res)
    return render_template("home/register.html")


@home.route("/logout/")
def logout():
    """
    退出登录
    """
    # 重定向到home模块下的登录。
    session.pop("user_id", None)
    session.pop("username", None)
    return redirect(url_for('home.index'))


@home.route("/artist/<int:id>")
def artist(id=None):
    """
    歌手页
    """
    song = Song.query.join(Artist, Song.singer == Artist.artistName).filter(Artist.id == id).all()
    hot_artist = Artist.query.limit(6).all()
    return render_template('home/artist.html', song=song, hot_artist=hot_artist)  # 渲染模板


@home.route("/play_song")
def playSong():
    """
    获取播放路径
    """
    song_id = request.args.get("id", "")  # 接收传递的参数歌曲ID
    song = Song.query.filter_by(id=int(song_id)).first()
    song.hits += 1
    db.session.add(song)
    db.session.commit()
    res = {}
    res['status'] = 1
    res['path'] = song.fileURL
    return jsonify(res)


@home.route("/toplist")
def toplist():
    top_song = Song.query.order_by(Song.hits.desc()).limit(30).all()
    hot_artist = Artist.query.limit(6).all()
    return render_template('home/toplist.html', top_song=top_song, hot_artist=hot_artist)  # 渲染模板


@home.route('/style_list')
def styleList():
    """
    曲风
    """
    type = request.args.get('type', 0, type=int)
    page = request.args.get('page', type=int)  # 获取page参数值
    print(page, 'type:', type)
    page_data1 = Tag.query.order_by(Tag.id.desc()).paginate(1, per_page=10)
    print('?')
    if type:
        page_data = Song.query.join(Tag).filter(
            Song.style == type, Tag.id == type).order_by(Song.style.desc()).paginate(page=page, per_page=10)
    else:
        page_data = Song.query.order_by(Song.style.desc()).paginate(page=page, per_page=10)
        print(page_data)
    return render_template('home/styleList.html', page_data1=page_data1, page_data=page_data, type=type)  # 渲染模板


@home.route('/artist_list')
def artistList():
    '''
    歌手列表
    '''
    type = request.args.get('type', 0, type=int)
    page = request.args.get('page', type=int)  # 获取page参数值
    if type:
        page_data = Artist.query.filter_by(style=type).paginate(page=page, per_page=10)
    else:
        page_data = Artist.query.paginate(page=page, per_page=10)
    return render_template('home/artistList.html', page_data=page_data, type=type)  # 渲染模板


# 发现音乐
@home.route('/search')
def search():
    keyword = request.args.get('keyword')  # 获取关键字
    page = request.args.get('page', type=int)  # 获取page参数值
    if keyword:
        keyword = keyword.strip()
        page_data = Song.query.filter(Song.songName.like('%' + keyword + '%')).order_by(Song.id).paginate(
            page=page, per_page=10)
    else:
        page_data = Song.query.order_by(Song.songName).paginate(page=page, per_page=10)
    return render_template('home/search.html', keyword=keyword, page_data=page_data)


@home.route('/modify_password', methods=['GET', 'POST'])
def modifyPassword():
    if request.method == 'POST':
        old_pwd = request.form.get("old_pwd")
        new_pwd = request.form.get("new_pwd")
        # 检查原始密码是否正确
        user = User.query.filter_by(id=session['user_id']).first()  # 获取用户信息
        res = {}
        if not user.check_pwd(old_pwd):
            res['status'] = -1
            res['message'] = '原始密码错误'
            return jsonify(res)
        # 更改密码
        try:
            user.pwd = new_pwd  # 对新密码加密
            db.session.add(user)
            db.session.commit()
            res['status'] = 1
            res['message'] = '密码修改成功'
            return jsonify(res)
        except:
            res['status'] = -2
            res['message'] = '密码修改错误'
            return jsonify(res)
    return render_template("home/modifyPassword.html")


# 用户忘记密码
@home.route('/manage_user_reset', methods=['GET', 'POST'])
def manageUserReset():
    if request.method == "POST":  # 提交注册表单
        username = request.form.get('usernameF')  # POST和GET提交都可以获取ID
        pwd = request.form.get('newpassword')
        user = User.query.filter_by(username=username).first()  # 获取用户信息

        # 获取用户信息
        if not user or user.flag != 0:
            res = {}
            res['status'] = -2
            res['message'] = '用户不存在'
            return jsonify(res)
        # 写入到user表
        try:
            # 重置密码
            user.pwd = pwd
            db.session.add(user)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '修改成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '修改失败'
        return jsonify(res)

    return render_template("home/managePasswordReset.html")


# 管理员重置密码
@home.route('/manage_admin_reset', methods=['GET', 'POST'])
def manageAdminReset():
    id = request.values['id']  # POST和GET提交都可以获取ID
    user = User.query.filter_by(id=id).first()  # 获取用户信息
    # 重置密码
    user.pwd = '12345'
    db.session.add(user)  # 添加数据
    db.session.commit()  # 提交数据
    res = {}
    res['status'] = 1
    res['message'] = '密码已重置'
    return jsonify(res)


@home.route("/collect")
@user_login
def collect():
    """
    收藏歌曲
    """
    song_id = request.args.get("id", "")  # 接收传递的参数歌曲ID
    user_id = session['user_id']  # 获取当前用户的ID
    print("用户id:",session["user_id"])
    print("session:",session)
    collect = Collect.query.filter_by(  # 根据用户ID和景区ID判断是否该收藏
        user_id=int(user_id),
        song_id=int(song_id)
    ).count()
    res = {}
    # 已收藏
    if collect == 1:
        res['status'] = 0
        res['message'] = '已经收藏'
    # 未收藏进行收藏
    if collect == 0:
        collect = Collect(
            user_id=int(user_id),
            song_id=int(song_id),
            score=10
        )
        db.session.add(collect)  # 添加数据
        db.session.commit()  # 提交数据
        res['status'] = 1
        res['message'] = '收藏成功'
    return jsonify(res)  # 返回json数据


@home.route("/collect_list")
@user_login
def collectList():
    page = request.args.get('page', type=int)  # 获取page参数值

    page_data = Collect.query.filter_by(user_id=session['user_id']).paginate(page=page,per_page=10)

    return render_template('home/collectList.html', page_data=page_data)


@home.route("/manage_artist_list")
@admin_login
def manageArtist():
    '''
    后台管理
    '''
    page = request.args.get('page', type=int)  # 获取page参数值
    page_data = Artist.query.join(Tag).filter(
        Tag.id == Artist.style
    ).order_by(Artist.id).paginate(page=page, per_page=10)
    for data in page_data.items:
        print(data)

    return render_template('home/manageArtist.html', page_data=page_data)


@home.route("/manage_admin_list")
@admin_login
def manageAdmin():
    '''
    后台管理
    '''

    page = request.args.get('page', type=int)  # 获取page参数值
    page_data = User.query.paginate(page=page, per_page=10)

    return render_template('home/manageAdmin.html', page_data=page_data)


@home.route("/manage_user_list")
@admin_login
def manageUser():
    '''
    后台管理
    '''

    page = request.args.get('page', type=int)  # 获取page参数值
    page_data = User.query.paginate(page=page, per_page=10)

    return render_template('home/manageUser.html', page_data=page_data)


@home.route("/manage_artist_add", methods=["GET", "POST"])
@admin_login
def manageArtistAdd():
    '''
    新增歌手
    '''
    tag_data = Tag.query.paginate(page=1, per_page=10)
    if request.method == "POST":  # 提交注册表单
        artistName = request.form.get("artistName")
        style = request.form.get("style")
        imgURL = request.form.get("imgURL")
        isHot = request.form.get("isHot")
        # 判断歌手是否存在
        artist = Artist.query.filter_by(artistName=artistName).first()  # 获取用户信息
        if artist:
            res = {}
            res['status'] = -2
            res['message'] = '该歌手已存在'
            return jsonify(res)
        # 写入到Artist表
        try:
            # 为Artist类属性赋值
            artist = Artist(
                artistName=artistName,
                style=int(style),
                imgURL=imgURL,
                isHot=int(isHot)
            )
            db.session.add(artist)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '添加成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '添加失败'
        return jsonify(res)
    return render_template('home/manageArtistAdd.html', tag_data=tag_data)


@home.route("/manage_user_add", methods=["GET", "POST"])
@admin_login
def manageAdminAdd():
    '''
    新增管理员
    '''

    if request.method == "POST":  # 提交注册表单
        print(1)
        username = request.form.get("username")
        flag = request.form.get("flag")
        print(username)
        # 判断用户是否存在
        user = User.query.filter_by(username=username).first()  # 获取用户信息
        res = {}
        if user and user.flag == 0:
            res = {}
            # 写入到User表
            try:
                # 为User类属性赋值
                user.flag = flag
                db.session.add(user)  # 添加数据
                db.session.commit()  # 提交数据
                res = {}
                res['status'] = 1
                res['message'] = '添加成功'
            except:
                res = {}
                res['status'] = -1
                res['message'] = '添加失败'
            return jsonify(res)

        else:
            res['status'] = -2
            res['message'] = '该用户不存在'
            return jsonify(res)

    return render_template('home/manageAdminAdd.html')


@home.route("/manage_artist_edit", methods=["GET", "POST"])
@admin_login
def manageArtistEdit():
    '''
    编辑歌手
    '''
    id = request.values['id']  # POST和GET提交都可以获取ID
    artist = Artist.query.filter_by(id=id).first()  # 获取用户信息
    if request.method == "POST":  # 提交注册表单
        # 更改Artist表
        artistName = request.form.get("artistName")
        print(artistName)
        style = request.form.get("style")
        isHot = request.form.get("isHot")
        try:
            artist.artistName = artistName
            artist.style = int(style)
            artist.isHot = int(isHot)
            db.session.add(artist)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '保存成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '保存失败'
        return jsonify(res)
    return render_template('home/manageArtistEdit.html', artist=artist)


@home.route("/manage_admin_edit", methods=["GET", "POST"])
@admin_login
def manageAdminEdit():
    id = request.values['id']  # POST和GET提交都可以获取ID
    user = User.query.filter_by(id=id).first()  # 获取用户信息
    form = userForm()
    if request.method == "POST":  # 提交注册表单
        # 更改User表
        username = request.form.get("username")
        flag = request.form.get("flag")
        print(username)
        print("user.flag", flag)
        user = User.query.filter_by(username=username).first()
        print(user)
        if user and user.flag == 1:
            try:
                user.username = username
                user.flag = int(flag)
                db.session.add(user)  # 添加数据
                db.session.commit()  # 提交数据
                res = {}
                res['status'] = 0
                res['message'] = '修改成功'
            except:
                res = {}
                res['status'] = 1
                res['message'] = '修改失败'
            return jsonify(res)
        else:
            res = {}
            res['status'] = 2
            res['message'] = '管理员不存在'
            return jsonify(res)

    return render_template('home/manageAdminEdit.html', user=user, form=form)


@home.route("/manage_artist_del")
@admin_login
def manageArtistDel():
    '''

    删除歌手

    '''

    id = request.args.get('id')  # 获取ID
    try:
        artist = Artist.query.get_or_404(int(id))
        db.session.delete(artist)
        db.session.commit()
        res = {}
        res['status'] = 1
        res['message'] = '删除成功'
    except:
        res = {}
        res['status'] = -1
        res['message'] = '删除失败'
    return jsonify(res)


@home.route("/manage_user_del")
@user_login
def manageUserDel():
    '''

    删除用户

    '''
    print(1)
    id = request.values['id']  # 获取ID
    print(id)
    try:

        user = User.query.get_or_404(id)
        print(user)
        db.session.delete(user)
        db.session.commit()
        session.pop('username')
        session.pop('user_id')
        res = {}
        res['status'] = 1
        res['message'] = '注销成功'
    except:
        res = {}
        res['status'] = -1
        res['message'] = '注销失败'
    return jsonify(res)


@home.route("/manage_song_list")
@admin_login
def manageSong():
    '''
    歌曲管理
    '''
    page = request.args.get('page', type=int)  # 获取page参数值
    page_data = Song.query.join(Tag).filter(
        Tag.id == Song.style
    ).order_by(Song.id).paginate(page=page, per_page=10)

    return render_template('home/manageSong.html', page_data=page_data)


@home.route("/manage_song_add", methods=["GET", "POST"])
@admin_login
def manageSongAdd():
    '''
    新增歌曲
    '''
    tag_data = Tag.query.paginate(page=1, per_page=10)
    if request.method == "POST":  # 提交注册表单
        songName = request.form.get("songName")
        singer = request.form.get("singer")
        style = request.form.get("style")
        fileURL = request.form.get("fileURL")
        artist = Artist.query.filter_by(artistName=singer).first()  # 获取歌手信息
        song = Song.query.filter_by(songName=songName).first()  # 获取歌曲信息

        if not artist:
            res = {}
            res['status'] = 0
            res['message'] = '该歌手不存在，请添加歌手'
            return jsonify(res)
        # 判断歌曲是否存在
        if song:
            res = {}
            res['status'] = -2
            res['message'] = '该歌曲已存在'
            return jsonify(res)
        # 写入到Song表
        # 为Song类属性赋值
        try:
            # 为Song类属性赋值
            song = Song(
                songName=songName,  # 歌曲名称
                singer=singer,  # 歌手
                style=style,  # 歌曲类型
                fileURL=fileURL  # 文件路径
            )
            db.session.add(song)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '添加成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '添加失败'
        return jsonify(res)

    return render_template('home/manageSongAdd.html', tag_data=tag_data)


@home.route("/manage_song_edit", methods=["GET", "POST"])
@admin_login
def manageSongEdit():
    '''
    编辑歌曲
    '''
    tag_data = Tag.query.paginate(page=1, per_page=10)
    id = request.values['id']  # POST和GET提交都可以获取ID
    song = Song.query.filter_by(id=id).first()
    if request.method == "POST":  # 提交注册表单
        # 更改Song表
        songName = request.form.get("songName")
        singer = request.form.get("singer")
        style = request.form.get("style")
        try:
            song.songName = songName
            song.singer = singer
            song.style = int(style)
            db.session.add(song)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '保存成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '保存失败'
        return jsonify(res)
    return render_template('home/manageSongEdit.html', song=song, tag_data=tag_data)


@home.route("/manage_song_del")
@admin_login
def manageSongDel():
    '''
    删除歌曲
    '''
    id = request.args.get('id')  # 获取ID
    try:
        song = Song.query.get_or_404(int(id))
        db.session.delete(song)
        db.session.commit()
        res = {}
        res['status'] = 1
        res['message'] = '删除成功'
    except:
        res = {}
        res['status'] = -1
        res['message'] = '删除失败'
    return jsonify(res)


@home.route("/upload", methods=["POST"])
@admin_login
def upload():
    """接受前端传送过来的文件"""
    file_obj = request.files.get("mp3")
    if file_obj is None:
        return "文件上传为空"
    # 直接使用文件上传对象保存
    path = str(int(time.time())) + ".mp3"
    file_obj.save(os.path.join(song_path, path))
    res = {}
    res['status'] = 1
    res['path'] = path
    return jsonify(res)


@home.route("/upload/img", methods=["POST"])
@admin_login
def uploadImg():
    """接受前端传送过来的文件"""
    file_obj = request.files.get("img")
    if file_obj is None:
        return "文件上传为空"
    # 直接使用文件上传对象保存
    path = str(int(time.time())) + ".jpg"
    file_obj.save(os.path.join(img_path, path))
    res = {}
    res['status'] = 1
    res['path'] = path
    return jsonify(res)


@home.route('/addHit')
def addHit():
    '''
    点击量加1
    '''
    id = request.args.get('id')
    song = Song.query.get_or_404(int(id))
    if not song:
        res = {}
        res['status'] = -1
        res['message'] = '歌曲不存在'
    # 更改点击量
    else:
        song.hits += 1
        db.session.add(song)
        db.session.commit()
        res = {}
        res['status'] = 1
        res['message'] = '播放次数加1'
    return jsonify(res)


'''new'''


# 类别管理
@home.route("/taglist")
@admin_login
def taglist():
    page = request.args.get('page', type=int)  # 获取page参数值
    page_data = Tag.query.paginate(page=page, per_page=5)

    return render_template('home/taglist.html', page_data=page_data)


# 类别添加
@home.route("/tagAdd", methods=["GET", "POST"])
@admin_login
def tagAdd():
    if request.method == "POST":  # 提交注册表单
        tagName = request.form.get("tagName")
        print(tagName)
        tag = Tag.query.filter_by(name=tagName).first()  # 获取歌曲信息
        print("tag:", tag)
        if tag:
            res = {}
            res['status'] = -2
            res['message'] = '该类别已存在'
            return jsonify(res)
        # 写入到Song表
        # 为Song类属性赋值
        else:
            # 为Song类属性赋值
            print(1)
            tag = Tag(
                name=tagName
            )
            print(1)
            db.session.add(tag)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '添加成功'
        # except:
        #     res = {}
        #     res['status'] = -1
        #     res['message'] = '添加失败'
        return jsonify(res)
    return render_template('home/tagAdd.html')


# 类别修改
@home.route("/tagEdit", methods=["GET", "POST"])
@admin_login
def tagEdit():
    id = request.values['id']  # POST和GET提交都可以获取ID
    tag = Tag.query.filter_by(id=id).first()
    print(type(tag.songs))
    if request.method == "POST":  # 提交注册表单
        # 更改Song表
        tagName = request.form.get("tagName")
        try:
            tag.name = tagName
            db.session.add(tag)  # 添加数据
            db.session.commit()  # 提交数据
            res = {}
            res['status'] = 1
            res['message'] = '保存成功'
        except:
            res = {}
            res['status'] = -1
            res['message'] = '保存失败'
        return jsonify(res)
    return render_template('home/tagEdit.html', tag=tag)


# 类别删除
@home.route("/tagDel")
@admin_login
def tagDel():
    id = request.args.get('id')  # 获取ID
    try:
        tag = Tag.query.get_or_404(int(id))
        db.session.delete(tag)
        db.session.commit()
        res = {}
        res['status'] = 1
        res['message'] = '删除成功'
    except:
        res = {}
        res['status'] = -1
        res['message'] = '删除失败'
    return jsonify(res)


# # 评论
# @home.route("/comment", methods=["GET", "POST"])
# def comment():
#     id = request.values['id']  # POST和GET提交都可以获取ID
#     print('id:', id)
#     page = request.args.get('page', type=int)  # 获取page参数值
#     page_data = Comment.query.join(Song).join(User).filter(
#         Comment.music_id == id,
#         Comment.music_id == Song.id,
#         Comment.user_id == User.id
#     ).paginate(page=page, per_page=5)
#     count = Comment.query.join(Song).join(User).filter(
#         Comment.music_id == id,
#         Comment.music_id == Song.id,
#         Comment.user_id == User.id
#     ).count()
#     return render_template('home/commentlist.html', page_data=page_data, music_id=id, count=count)

#
# @home.route("/ALLcommentlist", methods=["GET", "POST"])
# def ALLcommentlist():
#     page = request.args.get('page', type=int)  # 获取page参数值
#     page_data = Comment.query.join(Song).join(User).filter(
#         Comment.music_id == Song.id,
#         Comment.user_id == User.id
#     ).paginate(page=page, per_page=5)
#     return render_template('home/manage_commentlist.html', page_data=page_data)
#
#
# @home.route("/commentAdd", methods=["GET", "POST"])
# # @user_login
# def commentAdd():
#     if request.method == "POST":  # 提交注册表单
#         comment = request.form.get("comment")
#         music_id = request.form.get("music_id")
#         user_id = session.get('user_id')
#
#         if user_id:
#             try:
#                 comment = Comment(
#                     content=comment,
#                     music_id=music_id,
#                     user_id=session['user_id']
#                 )
#                 db.session.add(comment)  # 添加数据
#                 db.session.commit()  # 提交数据
#                 res = {}
#                 res['status'] = 1
#                 res['message'] = '评论成功'
#             except:
#                 res = {}
#                 res['status'] = -1
#                 res['message'] = '评论失败'
#         else:
#             res = {}
#             res['status'] = 2
#
#         return jsonify(res)
#
#
# # 评论删除
# @home.route("/comDel")
# @admin_login
# def comDel():
#     id = request.args.get('id')  # 获取ID
#     try:
#         comment = Comment.query.get_or_404(int(id))
#         db.session.delete(comment)
#         db.session.commit()
#         res = {}
#         res['status'] = 1
#         res['message'] = '删除成功'
#     except:
#         res = {}
#         res['status'] = -1
#         res['message'] = '删除失败'
#     return jsonify(res)

#取消收藏
@home.route("/resetcollect")
@user_login
def resetcollect():
    id = request.args.get('id')  # 获取ID
    print('id', id)
    collect = Collect.query.filter_by(
        song_id=id,
        user_id=session['user_id']).first()
    print(session['user_id'])

    db.session.delete(collect)
    db.session.commit()

    return redirect(url_for('home.collectList'))


# # 个性化推荐
# @home.route("/recommend")
# @user_login
# def recommend():
#     #page = request.args.get('page', type=int)  # 获取page参数值
#     data = Song.query.all()
#
#     a=test.reconmmend(session['user_id'])
#     if a:
#         data1 = []
#         for i in a:
#             data_m = Song.query.filter_by(id=i).all()
#             data1.append(data_m[0])
#         for i in data1:
#             print(i.id, i.songName)
#         message='基于用户'
#         return render_template('home/recommend.html', data=data1,message=message)
#     else:
#         get_label = Tag.query.all()
#         values = []
#
#         for i in get_label:
#             print('jinru')
#             get_count = Song.query.join(Collect).filter(Song.id == Collect.song_id,Song.style==i.id,Collect.user_id==session['user_id']).count()
#             values.append(get_count)
#
#         print(values)
#         print(values.index(max(values)))
#         a=values.index(max(values))
#         b=get_label[a].id
#         print(b)
#         data=Song.query.filter_by(style=b).order_by(Song.hits.desc()).limit(10).all()
#         message='无相似用户,基于标签'
#         return render_template('home/recommend.html', data=data,message=message)

# @home.route("/map")
# @user_login
# def map():
#     # 1.1 准备x，y轴坐标数据
#     get_name=Song.query.order_by(Song.hits.desc()).limit(10).all()
#     # 1.设置中文字体
#     mpl.rcParams['font.sans-serif'] = ['SimHei']
#     # 2.设置正常显示符号
#     mpl.rcParams['axes.unicode_minus'] = False
#     song_name = []
#     y=[]
#     for i in get_name:
#         song_name.append(i.songName)
#         y.append(i.hits)
#     x=range(len(song_name))
#     # 4. 绘制画布
#     plt.figure(1,figsize=(20, 8), dpi=100)
#
#     # 5.设置柱状图
#     plt.bar(x, y, width=0.5)
#     # 6.修改x轴刻度显示
#     plt.xticks(x, song_name)
#
#     # 7.添加网格显示
#     plt.grid(linestyle='--', alpha=0.5)
#
#     # 8. 添加标题
#     plt.title("音乐播放量前十",fontsize=20)
#     # 9. 添加描述
#     plt.xlabel("音乐名称")
#     plt.ylabel('播放量')
#
#     # '''
#     # 6.图像保存和显示
#     # '''
#     print(os.getcwd())
#     cwd=os.getcwd()
#     # if os.getcwd()!="D:/2103535526/FileRecv/音乐推荐python/music_online/app/static/picture":
#     #     print('进入')
#     os.chdir('D:/2103535526/FileRecv/音乐推荐python/music_online/app/static/picture')
#     plt.savefig("播放量前十.png")
#     # 4.显示
#     #plt.show()
#
#     plt.figure(2, figsize=(20, 8), dpi=100)
#     get_label=Tag.query.all()
#     # 3.设置标签列表
#     label = []
#     # 5. 设置饼图占比
#     values = []
#     # 4. 设置各项距离圆形n个半径
#     explode = []
#     for i in get_label:
#         label.append(i.name)
#         get_count=Song.query.filter_by(style=i.id).count()
#         values.append(get_count)
#         explode.append(0.01)
#     print(label)
#     print(values)
#     print(max(values))
#
#     # 6.绘制饼图且设置各种参数
#     patches, l_text, p_text = plt.pie(values, explode=explode, labels=label, autopct='%1.1f%%')
#     # 7.设置饼图字号
#     # 标签
#     for t in l_text:
#         t.set_size(20)
#     # 占比
#     for t in p_text:
#         t.set_size(16)
#
#     # 设置标题
#     plt.title("音乐库各类别歌曲量占比", fontsize=20)
#     plt.savefig('音乐库占比.png')
#     return render_template('home/map.html')


